package com.example.demo.common.util;

import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;

public class WordWriteUtil {

    private XWPFDocument document;

    private XWPFParagraphBuilder paragraphBuilder;

    private XWPFRunBuilder xwpfRunBuilder;

    public void createDocument() {
        document = new XWPFDocument();
    }

    public void addNewPage(XWPFDocument document, BreakType breakType) {
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.createRun().addBreak(breakType);
    }

    public void setCellText(XWPFTableCell cell, String text, String bgcolor, int width) {
        CTTc ctTc = cell.getCTTc();
        CTTcPr ctTcPr = ctTc.addNewTcPr();
        CTShd ctShd = ctTcPr.addNewShd();
        ctTcPr.addNewTcW().setW(BigInteger.valueOf(width));
        ctShd.setFill(bgcolor);
        ctTcPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        ctTc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
        cell.setText(text);
    }

    //设置页边距，1cm ≈ 567
    public void setDocumentMargin(XWPFDocument document, String left, String top, String right, String bottom) {
        CTSectPr sectPr = document.getDocument().getBody().isSetSectPr() ? document.getDocument().getBody().getSectPr() : document.getDocument().getBody().addNewSectPr();
        CTPageMar ctPageMar = sectPr.addNewPgMar();
        ctPageMar.setLeft(new BigInteger(left));
        ctPageMar.setTop(new BigInteger(top));
        ctPageMar.setRight(new BigInteger(right));
        ctPageMar.setBottom(new BigInteger(bottom));
    }

    //保存文档
    public void saveDocument(XWPFDocument document, String savePath) throws Exception {
        File file = new File(savePath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(file);
        document.write(fos);
        fos.close();
    }

    public XWPFDocument getDocument() {
        return document;
    }

    public void setDocument(XWPFDocument document) {
        this.document = document;
    }

    public XWPFParagraphBuilder getParagraphBuilder() {
        if (paragraphBuilder == null) {
            this.paragraphBuilder = new XWPFParagraphBuilder();
        }
        return paragraphBuilder;
    }

    public XWPFRunBuilder getRunBuilder() {
        if (xwpfRunBuilder == null) {
            this.xwpfRunBuilder = new XWPFRunBuilder();
        }
        return xwpfRunBuilder;
    }



}
